#!/bin/sh /etc/rc.common
# Copyright NetFoundry Inc.

START=65
STOP=65
USE_PROCD=1

prog=/usr/sbin/ziti-edge-tunnel

idfile=/etc/ziti/id.json
jwtfile=/etc/ziti/ca.jwt
certfile=/etc/ziti/id.crt
keyfile=/etc/ziti/id.key

log_opts="-s -t ziti"

interface="wan"

start_service() {
	enroll
  # commands to launch application
  if [ ! -f "$idfile" ]; then
		logger -p err $log_opts "identity is not enrolled"
		return 1
	fi

	procd_open_instance ziti-edge-tunnel
	procd_set_param command ${prog} run
	procd_append_param command -i ${idfile}
	procd_append_param command --dns=dnsmasq:/tmp/hosts

	procd_set_param respawn ${respawn_threshold:-3600} ${respawn_timeout:-5} ${respawn_retry:-5}
	procd_set_param stderr 1
	procd_set_param stdout 1
	procd_set_param pidfile /var/run/${prog}.pid

  procd_open_trigger
	for iface in $interface; do
	  logger $log_opts "adding interface trigger $iface"
	  procd_add_reload_interface_trigger $iface
	done
  procd_close_trigger
	procd_close_instance
}

reload_service() {
  stop
  start
}

enroll() {
	if [ -f "$idfile" ]; then
		logger $log_opts "enrollment $idfile exists"
	else
		logger $log_opts "enrolling with Ziti.."
		${prog} enroll -i ${idfile} -j ${jwtfile} -c ${certfile} -k ${keyfile} 2>&1 | logger -p info $log_opts
	fi
}